package com.beiing.tianshuai.tianshuai.freshnews;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.ShowImageWebView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DiscoveryPreviewActivity extends BaseActivity {

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.wv_content)
    ShowImageWebView mWvContent;
    @BindView(R.id.loading_background)
    View mLoadingBackground;

    private AlphaAnimation mHideAnimation;
    private boolean isOnPause;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_discovery_preview;
    }

    @Override
    protected void init() {
        ButterKnife.bind(this);
        CustomProgressDialog.showLoading(this, "", true);
        CustomProgressDialog.setCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        initToolbar();
        initData();
        initListener();
    }

    private void initToolbar() {
        mToolbarTvTitle.setText("预览");
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initData() {
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        String content = getHtml(intent.getStringExtra("content"));
        content = content
                .replaceAll("&lt;","<")
                .replaceAll("&gt;",">")
                .replaceAll("&quot;","")
                .replaceAll("&amp;","&");
        mTvTitle.setText(title);
        mWvContent.getSettings().setJavaScriptEnabled(true);
        mWvContent.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWvContent.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWvContent.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    CustomProgressDialog.stopLoading();
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        mWvContent.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mWvContent.setImageClickListener();
                mWvContent.parseHTML(view);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                showShortText("请检查您的网络设置");
            }
        });
        mWvContent.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
    }

    private void initListener() {
        CustomProgressDialog.setListener(new CustomProgressDialog.OnDismiss() {
            @Override
            public void onDismissListener() {
                setHideAnimation(mLoadingBackground, 888);
            }
        });
    }

    public void setHideAnimation(final View view, int duration) {
        if (null == view || duration < 0) {
            return;
        }

        if (null != mHideAnimation) {
            mHideAnimation.cancel();
        }
        // 监听动画结束的操作
        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(duration);
        mHideAnimation.setFillAfter(true);
        mHideAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                view.setVisibility(View.GONE);
            }
        });
        view.startAnimation(mHideAnimation);
    }

    private String getHtml(String html) {
        html = "<html> \n" +
                "<head> \n" +
                "<style type=\\\"text/css\\\"> \n" +
                "body {font-size:15px;}\n" +
                "</style> \n" +
                "</head> \n" +
                "<body>\n" +
                "<script type='text/javascript'>\n" +
                "window.onload = function(){\n" +
                "var $img = document.getElementsByTagName('img');\n" +
                "for(var p in $img){\n" +
                "$img[p].style.width = '90%'\n" +
                "$img[p].style.height ='auto'\n" +
                "$img[p].style.display ='block'\n" +
                "$img[p].style.margin ='0 auto'\n" +
                "}\n" +
                "}\n" +
                "\t\t\t\t</script>" +
                html + "\n" +
                "</body>\n" +
                "</html>";
        LogUtils.i(html, "HTML");
        return html;
    }

    /**
     * 当Activity执行onPause()时让WebView执行pause
     */
    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (mWvContent != null) {
                mWvContent.getClass().getMethod("onPause").invoke(mWvContent, (Object[]) null);
                isOnPause = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 当Activity执行onResume()时让WebView执行resume
     */
    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (isOnPause) {
                if (mWvContent != null) {
                    mWvContent.getClass().getMethod("onResume").invoke(mWvContent, (Object[]) null);
                }
                isOnPause = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        if (mWvContent != null) {
            mWvContent.getSettings().setBuiltInZoomControls(true);
            mWvContent.setVisibility(View.GONE);
            mWvContent.destroy();
            mWvContent = null;
        }
        isOnPause = false;
        super.onDestroy();
    }
}
